<template>
    <ElContainer class="admin-container">
        <el-header height="auto">
            <div class="row">
                <div class="col">
                    <el-form :inline="true" :model="formquery">
                        <el-form-item label="用户">
                            <el-input placeholder="请输入用户id、用户名、手机号" @change="start" v-model="like">
                            </el-input>
                        </el-form-item>
                        <el-form-item label="类型">
                            <el-select clearable v-model="formquery.type" style="width: 150px">
                                <el-option label="比赛" value="比赛"></el-option>
                                <el-option label="练习" value="练习"></el-option>
                                <el-option label="贡献" :value="['题解贡献', '测试点贡献']"></el-option>
                                <el-option label="金币" value="金币"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
            <div class="row mb-1">
                <div class="col">
                    <el-button @click="start" type="primary">查询</el-button>
                    <el-button type="primary" @click="dialogVisible = true">添加</el-button>
                </div>
            </div>



        </el-header>
        <el-main class="admin-main">
            <el-table :data="tableData" border height="100%" @sort-change="sortchange">
                <el-table-column prop="ID" sortable="custom" width="80px" label="ID"></el-table-column>
                <el-table-column prop="userid" label="userid" width="80px" sortable="custom"></el-table-column>
                <el-table-column prop="user.name" label="用户" width="180px"></el-table-column>
                <el-table-column prop="type" sortable="custom" width="80px" label="类型"></el-table-column>
                <el-table-column prop="num" label="积分" width="80px" sortable="custom"></el-table-column>
                <el-table-column prop="describe" label="描述" sortable="custom"></el-table-column>
                <el-table-column prop="atherid" width="80px" label="比赛id或题目id" sortable="custom"></el-table-column>
                <el-table-column prop="createdAt" sortable="custom" width="160px" label="创建时间"
                    :formatter="(row) => TimeYH(row.createdAt)"></el-table-column>
                <el-table-column prop="createdAt" label="操作" width="160px">
                    <template #default="scope">
                        <el-button @click="dialogVisible = true; Object.assign(ruleForm, assign({}, scope.row))"
                            type="warning">修改
                        </el-button>
                        <el-button @click="del(scope.row.ID)" type="danger">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-main>
        <el-footer>
            <el-pagination @current-change="handleCurrentChange" :page-size="Number(limit)" layout="prev, pager, next"
                :total="count"></el-pagination>
        </el-footer>
        <el-dialog v-model="dialogVisible" title="添加" width="800px">
            <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm"
                status-icon>
                <el-form-item label="用户" prop="userid">
                    <el-avatar :size="48" :src="ruleForm.user?.headportrait" @click="dialogVisible2 = true"></el-avatar>
                    <br />
                    <span>{{ ruleForm.user?.name }}</span>
                </el-form-item>
                <el-form-item label="类型" prop="type">
                    <el-select v-model="ruleForm.type">
                        <el-option label="练习" value="练习" />
                        <el-option label="比赛" value="比赛" />
                        <el-option label="题解贡献" value="题解贡献" />
                        <el-option label="测试点贡献" value="测试点贡献" />
                        <el-option label="金币" value="金币" />
                    </el-select>
                </el-form-item>
                <el-form-item label="积分" prop="num">
                    <el-input-number v-model="ruleForm.num" :min="1" :max="999" />
                </el-form-item>
                <el-form-item label="比赛id或题目id">
                    <el-input-number v-model="ruleForm.atherid" />

                </el-form-item>
                <el-form-item label="状态">
                    <el-radio-group v-model="ruleForm.state">
                        <el-radio :label="true" />
                        <el-radio :label="false" />
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="ruleForm.describe" type="textarea" />
                </el-form-item>
            </el-form>
            <el-dialog width="950px" v-model="dialogVisible2">
                <User v-bind="{ userhandleCurrentChange, tablekey }"></User>
            </el-dialog>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="resetForm($refs.ruleFormRef)">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </ElContainer>
</template>

<script setup lang="ts">
import { ElButton, ElContainer, ElFooter, ElHeader, ElInput, ElMain, ElMessage, ElMessageBox, ElPagination, ElTable, ElTableColumn, FormInstance, FormRules } from "element-plus";
import { assign, forEach } from 'lodash-es';
import {
    onMounted,
    reactive,
    ref,
    watch
} from "vue";
import { Iobj, asynccreateorupdateintegral, asyncdelintegral, asyncselectintegral } from "../../../api";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { TimeYH } from "../../../util/time";
import User from "../User/index.vue";

const dialogVisible = ref(false)
const dialogVisible2 = ref(false)
const ruleForm = reactive<Studycodemodel.Iintegral>({})
const formquery = reactive<Studycodemodel.Iintegral>({})
const sortable = ref<"DESC" | "ASC">("DESC");
const limit = ref(20);
const offset = ref(0);
const order = ref<keyof Studycodemodel.Iintegral>("ID");
const like = ref("");
function userhandleCurrentChange(data: Studycodemodel.Iuser) {
    ruleForm.userid = data.ID
    ruleForm.user = data
    dialogVisible2.value = false;
}
const tablekey: Array<keyof Studycodemodel.Iuser> = ["name", "ID"];

const rules = reactive<FormRules>({
    userid: [
        { required: true, trigger: 'change' },
    ],
    type: [
        { required: true, trigger: 'change' },
    ],
    num: [
        { required: true, trigger: 'blur' },
    ],
})

const tableData = ref<Studycodemodel.Iintegral[]>([]);

const ruleFormRef = ref<FormInstance>()


const count = ref<number>(0);

onMounted(() => {
    start()
});

async function resetForm(formEl?: FormInstance) {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            asynccreateorupdateintegral(ruleForm).then(e => {
                forEach(ruleForm, (e, k) => {
                    delete ruleForm[k]
                })
                dialogVisible.value = false
                start()
            })
        }
    })
}

async function start() {
    try {
        const obj: Iobj<Studycodemodel.Iintegral> = {
            _limit: limit.value,
            _offset: offset.value,
            _order: order.value,
            _sortable: sortable.value,
            ...formquery
        }
        if (like.value) {
            obj._keyword = [
                ['id', like.value],
                ['name', like.value],
                ['phonenum', like.value],
            ]
        }
        const data = await asyncselectintegral(obj)
        tableData.value = data.rows
        count.value = data.count
    } catch (e: any) {

        ElMessage.error(e);
    }
}


function handleCurrentChange(val: number) {
    offset.value = limit.value * (val - 1);
}

function sortchange(row: {
    order: string;
    prop: keyof Studycodemodel.Iintegral;
}) {
    const { prop } = row;
    if (row.order == "descending") {
        sortable.value = "DESC";
    } else {
        sortable.value = "ASC";
    }
    order.value = prop;
}


function del(ID: number) {
    try {
        ElMessageBox.confirm("是否删除该选项, 是否继续?", "提示", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
        })
            .then(async () => {
                await asyncdelintegral({ ID });
                ElMessage({
                    type: "success",
                    message: "删除成功!",
                });
                start();
            })
            .catch((e: string) => {
                ElMessage({
                    message: "删除失败" + e,
                    type: "error",
                });
            });
    } catch (e: any) {
        ElMessage({
            type: "info",
            message: "已取消删除",
        });
    }
}


watch([limit, offset, order, sortable], () => {
    start();
});
</script>

<style scoped>
a {
    text-decoration: none;
}
</style>

<style>
.admin-main {
    overflow: auto;
}

.admin-container {
    height: 100%;
}
</style>